
'''
Interface for the component server

'''


import httplib, httplib2, json
from urllib import urlencode

SERVER = 'http://ni-server.appspot.com/'
SERVER = 'http://localhost:8080/'

PLUGIN_PAGE = "plugin"
REVISION_PAGE = "revision"

http = httplib2.Http()

def put(page, vars, body=None):
    try:
        header, content = http.request(SERVER+page+'?'+urlencode(vars), "PUT", body=body)
    except AttributeError, e:
        print 'could not access server'
        return
    print 'SERVER PUT', content
    return json.loads(content)

def get(page, vars, body=None):
    try:
        header, content = http.request(SERVER+page+'?'+urlencode(vars), "GET", body=body)
    except AttributeError, e:
        print 'could not access server'
        return None
    print 'SERVER GET', content
    return json.loads(content)

def add_module(module):
    doc = module.__doc__
    name = module.__name__
    path = module.__path__
    
def add_plugin(name, doc, code, objects):
    body_content = {'code':code,
                    'doc':doc,
                    'name':name,
                    'objects':objects}
    body = json.dumps(body_content)
    return put(PLUGIN_PAGE, {}, body)
 
def all_plugins():
    return get(PLUGIN_PAGE, {})
    

def add_revision(plugin, revision, name, code, objects):
    body_content = {'code':code,
                    'parent':revision,
                    'plugin':plugin,
                    'name':name,
                    'objects':objects}
    body = json.dumps(body_content)
    return put(REVISION_PAGE, {}, body)


def revision_tree(plugin):
    return get(REVISION_PAGE, {'plugin':plugin})


def latest_revision(plugin):
    return get(REVISION_PATH, {'plugin':plugin, 'latest':True})




if __name__ == '__main__':
    def create_test_content():
        code = """
class TestNode(ni.Node):
    input = ni.Int()
    output = ni.Int()

"""
        plugin, revision = add_plugin("Test Plugin", "Test Docs", code, ["TestNode"])
        #add_revision(plugin, revision, "Test plugin rev" "rev docs", "print 'hello rev'", ["revobject"])
    create_test_content()
    plugins = all_plugins()
    for key, data in plugins.items():
        print data['latest_code']
    
    

